package guoan.service.weixin;

import guoan.core.common.WebConfig;
import guoan.domain.Adv;
import guoan.domain.AdvPay;
import guoan.domain.Keyword;
import guoan.service.AdvPayService;
import guoan.service.AdvService;
import guoan.service.AutoFormService;
import guoan.service.KeywordService;
import guoan.wechat4j.WechatSupport;
import guoan.wechat4j.response.ArticleResponse;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;

@Service
@Scope("prototype")
public class WechatService extends WechatSupport {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private KeywordService keywordService;
	@Autowired
	private AdvPayService advPayService;
	@Autowired
	private AdvService advService;
	@Autowired
	private AutoFormService autoFormService;
	@Value("${weixin.host}")
	private String host;

	public WechatService(HttpServletRequest request) {
		super(request);
	}

	public WechatService() {
	}

	/**
	 * 文本消息
	 */
	@Override
	protected void onText() {
		String content = super.wechatRequest.getContent().trim();
		// String msgId = wechatRequest.getMsgId();
		logger.info(content);
		if (!Strings.isNullOrEmpty(content)) {
			Keyword keyword = keywordService.findTop1ByKeyName(content);
			if (keyword != null) {
				if (WebConfig.KEYWORD_KEY_INFO_ADV.equals(keyword.getKeyInfo())) {
					Adv adv = advService.findOne(keyword.getKeyInfoId());
					if(adv!=null){
						if (adv.getType().equals("img")) {
							ArticleResponse item = new ArticleResponse();
							item.setTitle(adv.getTitle());
							item.setDescription(adv.getInfo());
							if(adv.getwUrl()!=null && !adv.getwUrl().equals("")){
								item.setUrl(adv.getwUrl());
							}else{
								item.setUrl("http://"+host+"/weixin/adv/content/" + adv.getId());
							}
							item.setPicUrl(adv.getImgUrl());
							responseNews(item);
						}else if (adv.getType().equals("text")) {
							responseText(adv.getInfo());
						}else if (adv.getType().equals("home")) {
							ArticleResponse item = new ArticleResponse();
							item.setTitle(adv.getTitle());
							item.setDescription(adv.getInfo());
							item.setUrl("/weixin/adv/index");
							item.setPicUrl(adv.getImgUrl());
							responseNews(item);
						}
					}else{
						AdvPay nomsg = advPayService.findOne("nomsg");
						if (nomsg != null) {
							responseText(nomsg.getInfo());
						}
					}
				}
			}else{
				AdvPay nomsg = advPayService.findOne("nomsg");
				if (nomsg != null) {
					responseText(nomsg.getInfo());
				}
			}
		} else {
			AdvPay nomsg = advPayService.findOne("nomsg");
			if (nomsg != null) {
				responseText(nomsg.getInfo());
			}
		}
	}

	/**
	 * 图片消息
	 */
	@Override
	protected void onImage() {
		AdvPay nomsg = advPayService.findOne("nomsg");
		if (nomsg != null) {
			responseText(nomsg.getInfo());
		}
	}

	/**
	 * 语音消息
	 */
	@Override
	protected void onVoice() {
		AdvPay nomsg = advPayService.findOne("nomsg");
		if (nomsg != null) {
			responseText(nomsg.getInfo());
		}
	}

	/**
	 * 视频消息
	 */
	@Override
	protected void onVideo() {
		AdvPay nomsg = advPayService.findOne("nomsg");
		if (nomsg != null) {
			responseText(nomsg.getInfo());
		}
	}

	/**
	 * 地理位置消息
	 */
	@Override
	protected void onLocation() {
		AdvPay nomsg = advPayService.findOne("nomsg");
		if (nomsg != null) {
			responseText(nomsg.getInfo());
		}
	}

	/**
	 * 链接消息
	 */
	@Override
	protected void onLink() {
		String Title = wechatRequest.getTitle();
		String Description = wechatRequest.getDescription();
		String Url = wechatRequest.getUrl();
		String MsgId = wechatRequest.getMsgId();

		String result = "链接消息Title:" + Title + ", Description:" + Description + ", Url:" + Url + ", MsgId:" + MsgId;
		logger.info(result);
	}

	/**
	 * 未知消息类型，错误处理
	 */
	@Override
	protected void onUnknown() {
		String msgType = wechatRequest.getMsgType();

		String result = "未知消息msgType:" + msgType;
		logger.info(result);

	}

	/**
	 * 扫描二维码事件
	 */
	@Override
	protected void scan() {
		String FromUserName = wechatRequest.getFromUserName();
		String Ticket = wechatRequest.getTicket();

		String result = "扫描二维码事件FromUserName:" + FromUserName + ", Ticket:" + Ticket;
		logger.info(result);
	}

	/**
	 * 订阅事件
	 */
	@Override
	protected void subscribe() {
		String FromUserName = wechatRequest.getFromUserName();
		// 用户未关注时扫描二维码事件,会多一个EventKey和Ticket节点
		String Ticket = wechatRequest.getTicket();

		String result = "订阅事件FromUserName:" + FromUserName;
		if (StringUtils.isNotBlank(Ticket)) {
			result = "扫描带场景值二维码事件FromUserName:" + FromUserName + ", Ticket:" + Ticket;
		}

		AdvPay advpay = advPayService.findOne("pay");
		if (advpay.getIsKey() == 1L) {
			String keyName = advpay.getKeyName();
			List<Keyword> keywords = keywordService.findTop9ByKeyName(keyName);
			if (keywords.size() > 0) {
				List<ArticleResponse> items = new ArrayList<ArticleResponse>();
				for (Keyword keyword : keywords) {
					if (WebConfig.KEYWORD_KEY_INFO_ADV.equals(keyword.getKeyInfo())) {
						Adv adv = advService.findOne(keyword.getKeyInfoId());
						if (adv.getType().equals("img")) {
							ArticleResponse item = new ArticleResponse();
							item.setTitle(adv.getTitle());
							item.setDescription(adv.getInfo());
							item.setUrl("http://"+host+"/weixin/adv/content/" + adv.getId());
							item.setPicUrl(adv.getImgUrl());
							items.add(item);
						}
					}
				}
				if (items.size() > 0) {
					responseNews(items);
				}
			}
			AdvPay nomsg = advPayService.findOne("nomsg");
			if (nomsg != null) {
				responseText(nomsg.getInfo());
			}

		} else {
			responseText(advpay.getInfo());
		}
		logger.info(result);
	}

	/**
	 * 取消订阅事件
	 */
	@Override
	protected void unSubscribe() {
		String FromUserName = wechatRequest.getFromUserName();
		String result = "取消订阅事件FromUserName:" + FromUserName;
		logger.info(result);
	}

	/**
	 * 点击菜单跳转链接时的事件推送
	 */
	@Override
	protected void view() {
		String link = super.wechatRequest.getEventKey();
		logger.info("点击菜单跳转链接时的事件推送link:" + link);
	}

	/**
	 * 自定义菜单事件
	 */
	@Override
	protected void click() {
		String key = super.wechatRequest.getEventKey();
		logger.info("自定义菜单事件eventKey:" + key);
	}

	/**
	 * 上报地理位置事件
	 */
	@Override
	protected void location() {
		String Latitude = wechatRequest.getLatitude();
		String Longitude = wechatRequest.getLongitude();
		String Precision = wechatRequest.getPrecision();
		String result = "上报地理位置事件Latitude:" + Latitude + ", Longitude:" + Longitude + ", Precision:" + Precision;
		logger.info(result);
	}

	/**
	 * 模板消息发送成功推送事件
	 */
	@Override
	protected void templateMsgCallback() {
		String MsgID = wechatRequest.getMsgId();
		String Status = wechatRequest.getStatus();
		String result = "模板消息发送成功推送事件MsgID:" + MsgID + ", Status:" + Status;
	}

	/**
	 * 弹出地理位置选择器的事件
	 */
	@Override
	protected void locationSelect() {
		String Location_X = wechatRequest.getSendLocationInfo().getLocation_X();
		String Location_Y = wechatRequest.getSendLocationInfo().getLocation_Y();
		String Scale = wechatRequest.getSendLocationInfo().getScale();
		String Label = wechatRequest.getSendLocationInfo().getLabel();
		String Poiname = wechatRequest.getSendLocationInfo().getPoiname();
		String result = "弹出地理位置选择器的事件Location_X:" + Location_X + ", Location_Y:" + Location_Y + ", Scale:" + Scale
				+ ", Label:" + Label + ", Poiname:" + Poiname;
		logger.info(result);
	}

	/**
	 * 弹出拍照或者相册发图的事件
	 */
	@Override
	protected void picPhotoOrAlbum() {
		String Count = wechatRequest.getSendPicsInfo().getCount();
		String PicMd5Sum = "";
		if (StringUtils.isNotBlank(Count) && !Count.equals("0")) {
			PicMd5Sum = wechatRequest.getSendPicsInfo().getItem().get(0).getPicMd5Sum();
		}
		String result = "弹出系统拍照发图的事件Count:" + Count + ", PicMd5Sum:" + PicMd5Sum;
		logger.info(result);
	}

	/**
	 * 弹出系统拍照发图的事件
	 */
	@Override
	protected void picSysPhoto() {
		String Count = wechatRequest.getSendPicsInfo().getCount();
		String result = "弹出系统拍照发图的事件Count:" + Count;
		logger.info(result);
	}

	/**
	 * 弹出微信相册发图器的事件推送
	 */
	@Override
	protected void picWeixin() {
		String Count = wechatRequest.getSendPicsInfo().getCount();
		String result = "弹出系统拍照发图的事件Count:" + Count;
		logger.info(result);
	}

	/**
	 * 扫码推事件
	 * 
	 */
	@Override
	protected void scanCodePush() {
		String ScanType = wechatRequest.getScanCodeInfo().getScanType();
		String ScanResult = wechatRequest.getScanCodeInfo().getScanResult();
		String result = "扫码推事件ScanType:" + ScanType + ", ScanResult:" + ScanResult;
		logger.info(result);
	}

	/**
	 * 扫码推事件且弹出“消息接收中”提示框的事件
	 */
	@Override
	protected void scanCodeWaitMsg() {
		String ScanType = wechatRequest.getScanCodeInfo().getScanType();
		String ScanResult = wechatRequest.getScanCodeInfo().getScanResult();
		String result = "扫码推事件ScanType:" + ScanType + ", ScanResult:" + ScanResult;
		logger.info(result);
	}

}